package com.luocc.ccdemo.ui

import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageButton
import android.widget.TextView
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.luocc.ccdemo.R
import com.luocc.ccdemo.common.OnItemClickListener
import com.luocc.ccdemo.common.VideoListAdapter
import com.luocc.ccdemo.entity.Video
import com.luocc.ccdemo.vm.VideoViewModel

class VideoFavoritesFragment : Fragment() {
    private var mClearDialog: AlertDialog? = null
    private var mOperationDialog: Dialog? = null
    private var mClear: ImageButton? = null
    private lateinit var mRecyclerView: RecyclerView
    private lateinit var mEmptyView: TextView

    private lateinit var mContext: Context
    private lateinit var mAdapter: VideoListAdapter

    private lateinit var mVideoViewModel: VideoViewModel

    private val mItemClickListener = object : OnItemClickListener<Video> {
        override fun onClick(position: Int, obj: Video) {
            showItemDialog(obj)
        }
    }

    override fun onAttach(context: Context) {
        super.onAttach(context)
        mContext = context
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mVideoViewModel = ViewModelProvider(this).get(VideoViewModel::class.java)
        mVideoViewModel.getFavorites().observe(this) {
            Log.d(TAG, "onCreate: 更新")
            mAdapter.submitList(it)
            checkEmpty(it.isEmpty())
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.fragment_video_favorites, container, false)
        val back = view.findViewById<ImageButton>(R.id.back)
        mClear = view.findViewById(R.id.clear)
        back.setOnClickListener { activity?.onBackPressed() }
        mClear?.setOnClickListener { showClearDialog() }
        mRecyclerView = view.findViewById(R.id.history_list)
        mEmptyView = view.findViewById(R.id.empty_display)
        initRecyclerView()
        return view
    }

    private fun initRecyclerView() {
        val manager = LinearLayoutManager(mContext)
        manager.orientation = LinearLayoutManager.VERTICAL
        mAdapter = VideoListAdapter(mContext)
        mAdapter.setOnItemClickListener(mItemClickListener)
        mRecyclerView.layoutManager = manager
        mRecyclerView.adapter = mAdapter
    }

    private fun showClearDialog() {
        if (mClearDialog == null) {
            mClearDialog = AlertDialog.Builder(context)
                .setMessage("确定要清除所有收藏记录吗?")
                .setNegativeButton("取消") { _, _ -> }
                .setPositiveButton("确认") { _, _ ->
                    mVideoViewModel.clearFavorites()
                }
                .create()
        }
        mClearDialog?.let {
            if (!it.isShowing) {
                it.show()
            }
        }
    }

    private fun checkEmpty(empty: Boolean) {
        Log.d(TAG, "checkEmpty: empty = $empty")
        mClear?.let {
            it.isEnabled = !empty
            val drawable = if (empty) ResourcesCompat.getDrawable(
                resources, R.mipmap.clear_disabled, null
            ) else ResourcesCompat.getDrawable(resources, R.mipmap.clear, null)
            it.setImageDrawable(drawable)
        }
        if (empty) {
            mRecyclerView.visibility = View.GONE
            mEmptyView.visibility = View.VISIBLE
        } else {
            mRecyclerView.visibility = View.VISIBLE
            mEmptyView.visibility = View.GONE
        }
    }

    private fun showItemDialog(video: Video) {
        if (mOperationDialog == null) {
            val dialog = Dialog(mContext, R.style.BottomDialogStyle)
            val view = layoutInflater.inflate(R.layout.video_click_popup, view as ViewGroup, false)
            dialog.setContentView(view)
            dialog.window?.let {
                it.setGravity(Gravity.CENTER)
                it.setLayout(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                it.setWindowAnimations(R.style.BottomDialogAnimation)
                val layoutParams = it.attributes
                val bounds = it.windowManager.currentWindowMetrics.bounds
                layoutParams.width = bounds.width() / 3 * 2
                it.attributes = layoutParams
            }
            dialog.setCanceledOnTouchOutside(true)
            mOperationDialog = dialog
        }
        mOperationDialog?.findViewById<TextView>(R.id.video_title)?.text = video.title
        mOperationDialog?.findViewById<Button>(R.id.watch)?.setOnClickListener {
            val bundle = Bundle(1)
            bundle.putParcelable("video", video)
            findNavController().navigate(
                R.id.action_videoFavoritesFragment_to_videoPlayingFragment,
                bundle
            )
            mOperationDialog?.dismiss()
        }

        mOperationDialog?.findViewById<Button>(R.id.delete)?.setOnClickListener {
            mVideoViewModel.delete(video.id)
            mOperationDialog?.dismiss()
        }
        mOperationDialog?.show()
    }

    companion object {
        private const val TAG = "LC_VideoHistoryFragment"
    }
}